from flask import render_template, session, current_app, jsonify, request
from info import constants
from info.models import User, Category, News
from info.utils.response_code import RET
from . import index_blue


@index_blue.route('/news_list')
def news_list():
    """
    参数名:
        cid: 分类id
        page; 页数
        per_page: 每页多少条数据
    """
    cid = request.args.get("cid", 1)
    page = request.args.get("page", 1)
    per_page = request.args.get("per_page", 10)

    # 参数校验
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except:
        return jsonify(errno=RET.PARAMERR, errmsg="参数1错误")

    # cid为1时,表示查询全部,error_out为True时,若分页为0或超出范围会抛出404错误
    filters = []
    if cid != 1:
        filters.append(News.category_id == cid)
    filters.append(News.status ==0)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    news_list = []
    news_models = paginate.items
    total_page = paginate.pages
    current_page = paginate.page

    for new in news_models:
        news_list.append(new.to_basic_dict())

    data = {
        "news_list": news_list,
        "total_page": total_page,
        "current_page": current_page
    }

    return jsonify(errno=RET.OK, errmsg="成功", data=data)


@index_blue.route('/')
def index():
    # 登录后,会再次调用此函数.此时根据session数据,获取用户数据
    user_id = session.get("user_id", None)
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger(e)

    # 添加分类(categorys_list): 1. 查询数据库; 2. 将查询结果遍历编入列表中 .3  前端实现
    categorys, categorys_list = None, []
    try:
        categorys = Category.query.all()
    except:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    for category in categorys if categorys else []:
        categorys_list.append(category.to_dict())

    # 点击排行(click_news_list): 1. 查询数据库; 2. 将查询结果遍历编入列表; 3. 前端实现
    news_models, click_news_list = None, []
    try:
        news_models = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    for new in news_models if news_models else []:
        click_news_list.append(new.to_basic_dict())

    # 拼接返回数据字典
    data = {
        # 模型中定义的to_dict
        "user": user.to_index_dict() if user else None,
        "categorys_list": categorys_list,
        "click_news_list": click_news_list
    }
    return render_template("news/index.html", data=data)


@index_blue.route('/favicon.ico')
def favicon():
    return current_app.send_static_file("news/favicon.ico")
